<template>
  <div>
    <div class="self-box">
      <Row class="smart-query-form-row">
          <div class="FolderDic">
            <span>
            <div class="FolderDic" @click="selectFolderByPath(rootObj,0)">{{ rootObj.fileName}}</div>
            <div>/</div>
            </span>
            <span v-for="(item,index) in folderObjList" :key="index">
            <div class="FolderDic" @click="selectFolderByPath(item,index)">{{ item.fileName}}</div>
            <div>/</div>
            </span>
          </div>
        </Row>
      <Card class="warp-card">

        <!-------操作按钮行 begin------->
        <Row class="marginBottom10">
          <Form :model="searchForm" class="tools" inline ref="searchForm">
            <FormItem prop="type">
              <Select
                style="width: 160px"
                placeholder="File Type"
                v-model="searchForm.fileType"
              >
              <Option value="">All</Option>
              <Option v-for="item in fileTypeList" :key="item" :value="item.configKey">{{item.configKey}}</Option>
              </Select>
            </FormItem>
            <FormItem>
              <ButtonGroup>
                <Button
                  @click="find"
                  icon="ios-search"
                  type="primary"
                  v-privilege="'filemanage-file-list-query'"
                  >Search</Button
                >
              </ButtonGroup>
            </FormItem>
          </Form>
          <div class="operateBtn">
          <Button
            @click="newFileForm"
            class="marginLeft10"
            type="primary"
            size="small"
            v-privilege="'filemanage-create-folder'"
            >New Folder</Button
          >
          <!-- <Upload
            :action="uploadUrl"
            :headers="uploadHeader"
            :onError="uploadError"
            :onSuccess="uploadSuccess"
            :showUploadList="false"
          >
            <Button size="small" class="marginLeft10" type="primary"
              >上传模板文件</Button
            >
          </Upload> -->
          <!-- <Upload
            :action="uploadUrl"
            :headers="uploadHeader"
            :onError="uploadErrorSingle"
            :onSuccess="uploadSuccessSingle"
            :showUploadList="false"
            multiple
          > -->
          <Button 
            size="small" 
            class="marginLeft10" 
            type="primary" 
            @click="upload.show = true"
            v-privilege="'filemanage-file-upload'"
              >Upload</Button
            >
          <!-- </Upload> -->
          <Button
            @click="downloadFile"
            type="primary"
            class="marginLeft10"
            size="small"
            v-privilege="'filemanage-file-download'"
            >Download</Button
          >
          <Button
            @click="showAddPeonyForm"
            type="primary"
            class="marginLeft10"
            size="small"
            v-privilege="'filemanage-file-move'"
            >Move</Button
          >
          <Button
            @click="showResetFileForm"
            type="primary"
            class="marginLeft10"
            size="small"
            v-privilege="'filemanage-file-rename'"
            >Rename</Button
          >
          <Button
            @click="deleteFile"
            class="marginLeft10"
            icon="ios-trash-outline"
            size="small"
            type="error"
            v-privilege="'filemanage-file-delete'"
            >Delete</Button
          >
          </div>
        </Row>
        <!-- <Table
          :columns="columns"
          :data="tableData"
          border
          highlight-row
          ref="mainTable"
          @on-row-click="selectTable"
        ></Table> -->
        <Table
          :columns="columns"
          :data="tableData"
          border
          highlight-row
          ref="mainTable"
          @on-selection-change="selectChange"
        ></Table>
        <Page
          :current="searchForm.pageNum"
          :page-size="searchForm.pageSize"
          :page-size-opts="[10, 20, 30, 50, 100]"
          :total="total"
          @on-change="changePage"
          @on-page-size-change="changePageSize"
          show-elevator
          show-sizer
          show-total
          class="smart-query-table-page"
        ></Page>
      </Card>
    </div>
    <Modal
      :footer-hide="true"
      title="New Folder"
      v-show="fileModal.show"
      @on-cancel="fileFormClose"
      width="500"
    >
      <FileListForm
        :isUpdate="fileModal.isUpdate"
        :updateData="fileModal.updateData"
        :parentFolderId="currentFileID"
        @on-form-close="fileFormClose"
      />
    </Modal>
    <Modal
      :footer-hide="true"
      title="Move File"
      v-model="saveModal.show"
      @on-cancel="saveFormClose"
      width="500"
    >
      <PeonyListForm
        :moveList="selectFolderObject"
        @on-form-close="saveFormClose"
      />
    </Modal>
    <Modal
      :footer-hide="true"
      title="Upload"
      v-model="upload.show"
      @on-cancel="uploadClose"
      width="500"
    >
      <UploadFile
        :parentFolderId='currentFileID'
        @on-form-close="uploadClose"
        @queryFile="queryList"
        :show="upload.show"
      />
    </Modal>
    <Modal
      :footer-hide="true"
      :title="resetModal.isUpdate ? 'Rename' : 'New Folder'"
      v-model="resetModal.show"
      @on-cancel="resetFormClose"
      width="400"
    >
      <ResetListForm
        :isUpdate="resetModal.isUpdate"
        :updateData="resetModal.updateData"
        :parentFolderId = 'currentFileID'
        @on-form-close="resetFormClose"
      />
    </Modal>
  </div>
</template>

<script>
import { fileApi } from '@/api/file.js';
import { assetsApi } from '@/api/assets.js';
import UploadFile from '@/components/uploadFileMui/index';
import PeonyListForm from './components/peony-list-form';
import FileListForm from './components/add-list-form';
import ResetListForm from './components/reset-list-form';
import { FILE_TYPE, SERVICE_TYPE } from '@/constants/file';
import Cookies from 'js-cookie';
import { TOKEN_KEY } from '@/lib/cookie';

export default {
  name: 'FileList',
  components: {
    PeonyListForm,
    FileListForm,
    ResetListForm,
    UploadFile
  },
  props: {},
  data () {
    return {
      saveModal: {
        show: false,
        isUpdate: false,
        updateData: null
      },
      fileModal: {
        show: false,
        isUpdate: false,
        updateData: null
      },
      resetModal: {
        show: false,
        isUpdate: false,
        updateData: null
      },
      batchDeleteModal: {
        show: false
      },
      upload: {
        show: false
      },
      // 数据量
      total: null,
      // 查询参数
      searchForm: {
        fileClass: null, // 标识文件文档 还是视频  音频  压缩包之类
        // fileMode: 1,       //文件是普通文件 0  还是文件夹  1
        fileName: null, // 文件名称关键字
        fileType: null, // 文件类型 就是JPEG MP3 MP4 AVI 等等
        pageNum: 1,
        pageSize: 10,
        parentFolderId: 0, // 初始化文件夹父节点为0
        searchCount: true, // 是否查询总条数
        moduleType: 3 // 功能模块编号
      },
      currentid: 0,
      selectFolderObject: [],
      // 表头
      columns: [
        {
          type: 'selection',
          width: 30,
          align: 'center'
        },
        {
          width: 300,
          title: 'Folder Name',
          key: 'fileName',
          render: (h, params) => {
            if (params.row.fileMode == 1 || params.row.fileMode == '1') {
              return h(
                'div',
                {
                  style: {
                    cursor: 'pointer'
                  },
                  on: {
                    click: () => {
                      this.selectFolder(params.row, 10000);
                    }
                  }
                },
                [
                  h('i', {
                    class: 'ivu-icon ivu-icon-md-albums',
                    style: {
                      fontSize: '20px',
                      color: '#ded81b',
                      marginRight: '9px'
                    }
                  }
                  ),
                  h(
                    'span', {}, params.row.fileName
                  )

                ]
              );
            } else {
              return h(
                'div', {}, params.row.fileName
              );
            }
          }
          // render: (h, params) => {
          //     let actions = [
          //       {
          //         title: params.row.fileName,
          //         action: () => {
          //           this.selectFolder(params.row,10000);
          //         },
          //       },
          //     ];
          //     return this.$tableAction(h, actions);
          // }
        },
        {
          title: 'Type',
          key: 'fileType'
        },
        {
          title: 'Size',
          key: 'fileSize'
        },
        {
          title: 'Creation Time',
          key: 'createTime'
        },
        {
          title: 'Uploaded Time',
          key: 'updateTime'
        },
        {
          title: 'User',
          key: 'createByName'
        }
      ],
      // table数据
      tableData: [],
      // 删除id
      delId: null,
      mainTableSelectArray: [],
      breadArr: [],
      data2: [
        {
          title: '一级 1',
          id: 2,
          children: [
            {
              title: '二级 1-1',
              id: 3,
              children: [
                {
                  title: '三级 1-1-2',
                  id: 4,
                  children: [
                    {
                      title: '四级 1-1-3-4',
                      id: 5
                    }
                  ]
                },
                {
                  title: '三级 1-1-2',
                  id: 6
                }
              ]
            }
          ]
        }
      ],
      // 根文件夹
      rootObj: {
        fileMode: 1,
        fileName: 'Files',
        id: 0,
        parentFolderId: 0
      },
      // 当前文件夹
      currentFolder: null,
      // 当前文件ID
      currentFileID: 0,
      // 文件夹id列表
      folderObjList: [],
      fileTypeList: []
    };
  },
  computed: {
    uploadHeader: function () {
      let header = {
        'x-access-token': Cookies.get(TOKEN_KEY)
      };
      return header;
    },
    uploadUrl: function () {
      let baseUrl = fileApi.fileUploadLocalUrl;
      switch (this.searchForm.fileLocationType) {
        case 2:
          baseUrl = fileApi.fileUploadAliUrl;
          break;
        case 3:
          baseUrl = fileApi.fileUploadQiNiuUrl;
          break;
        default:
          break;
      }
      let url = baseUrl + this.searchForm.moduleType;
      console.log('upload url:' + url);
      return url;
    },
    // 文件业务类型
    moduleTypes: function () {
      let array = [];
      for (let item in SERVICE_TYPE) {
        let obj = {};
        obj.desc = SERVICE_TYPE[item].desc;
        obj.value = SERVICE_TYPE[item].value;
        array.push(obj);
      }
      return array;
    }
  },
  watch: {},
  filters: {},
  created () {
    this.folderObjList = [];
    // 初始化根目录
    this.queryList();
    this.getFileType();
    // this.breadArr = this.getParentId(this.data2, 3).reverse();
  },
  methods: {
    async getFileType () {
      let res = await assetsApi.getOneGroup({ group: 'file_type' });
      this.fileTypeList = res.data;
    },
    // 新增
    addNew () {
      // this.$router.push({ path: "/email/send-mail" });
    },
    // 重置
    reset () {
      this.$refs.searchForm.resetFields();
      this.searchForm.startDate = null;
      this.searchForm.endDate = null;
      this.$set(this.searchForm, 'endDate', null);
      this.find();
    },
    // 删除确定
    async deleteSure (data) {
      this.$Spin.show();
      let param = [];
      data.forEach(item => {
        let obj = {
          fileId: item.id,
          fileMode: item.fileMode
        };
        param.push(obj);
      });
      let res = await fileApi.deleteFile(param);
      this.$Message.success('Delete success');
      this.$Spin.hide();
      this.queryList();
    },
    // 删除操作
    deleteFile () {
      if (!this.selectMessage()) return;
      this.$Modal.confirm({
        title: 'Kindly Reminder',
        content: 'Are you sure to delet the selected items?',
        onOk: () => {
          this.deleteSure(this.selectFolderObject);
        },
        okText: 'Confirm',
        cancelText: 'Cancel'
      });
    },
    // 查询
    find () {
      this.searchForm.pageNum = 1;
      this.searchForm.pageSize = 10;
      this.queryList();
    },
    // 更改分页查询条数
    changePageSize (pageSize) {
      this.searchForm.pageNum = 1;
      this.searchForm.pageSize = pageSize;
      this.queryList();
    },
    // 获取邮件数据
    async queryList () {
      this.$Spin.show();
      let res = await fileApi.queryFileManageList(this.searchForm);
      this.$Spin.hide();
      this.tableData = res.data.list;
      // 获取文件夹列表
      this.total = res.data.total;
      if (res.data.pages < this.searchForm.pageNum) {
        this.searchForm.pageNum = res.data.pages;
      }
    },
    // 获取文件夹路径
    getCurrentFilePath () {
      // 默认列表中第一个文件
      this.rootObj = this.tableData[0];
    },
    // 页码改变
    changePage (pageNum) {
      this.searchForm.pageNum = pageNum;
      this.queryList();
    },
    showAddPeonyForm () {
      if (!this.selectMessage()) return;
      this.saveModal.isUpdate = false;
      this.saveModal.show = true;
    },
    showEditPeonyForm (updateObject) {
      this.saveModal.isUpdate = true;
      this.saveModal.updateData = updateObject;
      this.saveModal.show = true;
    },
    saveFormClose () {
      this.saveModal.show = false;
      this.selectFolderObject = [];
      this.queryList();
    },
    uploadClose () {
      this.upload.show = false;
      this.queryList();
    },
    showAddFileForm () {
      this.fileModal.isUpdate = false;
      this.fileModal.show = true;
    },
    showEditFileForm (updateObject) {
      this.fileModal.isUpdate = true;
      this.fileModal.updateData = updateObject;
      this.fileModal.show = true;
    },
    fileFormClose () {
      this.fileModal.show = false;
    },
    showResetFileForm () {
      if (!this.selectMessage()) return;
      this.resetModal.isUpdate = true;
      this.resetModal.updateData = this.selectFolderObject[0];
      this.resetModal.show = true;
    },
    selectMessage () {
      if (this.selectFolderObject.length === 0) {
        this.$Message.warning('请选择要操作的文件夹或文件');
        return false;
      }
      return true;
    },
    newFileForm () {
      this.resetModal.isUpdate = false;
      this.resetModal.updateData = null;
      this.resetModal.show = true;
    },
    showResetEditFileForm (updateObject) {
      this.resetModal.isUpdate = true;
      this.resetModal.updateData = updateObject;
      this.resetModal.show = true;
    },
    resetFormClose () {
      this.resetModal.show = false;
      this.selectFolderObject = [];
      this.queryList();
    },
    // 校验是否有选中
    validateMainTableSelection () {
      this.mainTableSelectArray = this.$refs.mainTable.getSelection();
      if (this.mainTableSelectArray.length < 1) {
        this.$Message.error('请选择至少一条数据');
        return false;
      }
      return true;
    },
    // 下载
    async downloadFile () {
      if (!this.validateMainTableSelection()) return;
      let arr = [];
      this.mainTableSelectArray.forEach(item => {
        let obj = {
          fileMode: item.fileMode,
          id: item.id
        };
        arr.push(obj);
      });
      let res = await fileApi.downFile({ fileModeList: arr });
      // window.open(res);
    },
    // 上传成功钩子
    async uploadSuccess (e) {
      if (!e.success) {
        console.error(e);
        return this.uploadError();
      }
      this.$Spin.show();
      let reqBody = {
        moduleId: 1,
        moduleType: this.searchForm.moduleType ? this.searchForm.moduleType : 1,
        fileLocationType: this.searchForm.fileLocationType
          ? this.searchForm.fileLocationType
          : 1,
        fileName: e.data.fileName,
        filePath: e.data.filePath
      };
      let rep = await fileApi.addFile(reqBody);
      this.$Spin.hide();
      this.$Message.success('Upload success');
      this.find();
    },
    // 上传失败钩子
    uploadError (e) {
      this.$Message.error('Upload error, please retry!');
      console.error(e);
      this.find();
    },
    // 上传成功钩子
    async uploadSuccessSingle (e) {
      if (!e.success) {
        console.error(e);
        return this.uploadErrorSingle();
      }
      this.$Spin.show();
      let reqBody = {
        moduleId: 1,
        moduleType: this.searchForm.moduleType ? this.searchForm.moduleType : 1,
        fileLocationType: this.searchForm.fileLocationType
          ? this.searchForm.fileLocationType
          : 1,
        fileName: e.data.fileName,
        filePath: e.data.filePath
      };
      let rep = await fileApi.addFile(reqBody);
      this.$Spin.hide();
      this.$Message.success('Upload success');
      this.find();
    },
    // 上传失败钩子
    uploadErrorSingle (e) {
      this.$Message.error('Upload error, please retry!');
      console.error(e);
      this.find();
    },
    // 单机行
    selectTable (item) {
      console.log(item, 12345);
    },
    selectChange (data) {
      this.selectFolderObject = data;
    },
    // 查询文件夹下的文件
    selectChild () {
      this.currentFileID = this.currentFolder.id;
      console.log('currentFolder:' + this.currentFileID);
      this.searchForm.parentFolderId = this.currentFolder.id;
      this.childFile();
    },
    // 从文件目录中选中文件加
    selectFolderByPath (data, index) {
      console.log('selectFolderByPath:');
      if (index === 0) {
        this.folderObjList = [];
      } else {
        this.folderObjList = this.folderObjList.slice(0, index);
      }
      this.selectFolder(data);
    },
    selectFolder (data) {
      this.currentFolder = data;
      console.log('selectFolder:CurrentFolderId=' + this.currentFolder.id);
      // 判断当前是否是文件夹，如果文件夹
      if (data.fileMode == 1) {
        // 点击文件夹查询
        if (data.fileName != 'Files') {
          this.folderObjList.push(data);
        }
        this.currentFileID = this.currentFolder.id;
        this.searchForm.parentFolderId = this.currentFolder.id;
        this.childFile();
      } else {
        // 点击文件展示文件详情
      }
    },
    async childFile () {
      this.$Spin.show();
      let searchForm = {
        // fileMode: 1,       //文件是普通文件 0  还是文件夹  1
        pageNum: 1,
        pageSize: 10,
        parentFolderId: this.currentFileID, // 初始化文件夹父节点为0
        searchCount: true, // 是否查询总条数
        moduleType: 3
      };
      let res = await fileApi.queryFileManageList(searchForm);
      this.$Spin.hide();
      this.tableData = res.data.list;
      // 获取文件夹列表
      // this.getCurrentFilePath();
      this.total = res.data.total;
      // 选择清空
      this.currentid = 0;
      this.selectFolderObject = [];
      if (res.data.pages < this.searchForm.pageNum) {
        this.searchForm.pageNum = res.data.pages;
      }
    },
    getParentId (list, id) {
      for (let i in list) {
        if (list[i].id == id) {
          return [list[i]];
        }
        if (list[i].children) {
          let node = this.getParentId(list[i].children, id);
          if (node !== undefined) {
            return node.concat(list[i]);
          }
        }
      }
    }
  }
};
</script>
<style lang="less" scoped>
.nav-file {
  height: 50px;
  display: flex;
  align-items: center;
}
.ivu-icon-md-albums{
  font-size: 20px;
  color: yellow;
}
.FolderDic{
  div{
    display:inline-block;
    height:25px;line-height:25px;
    font-size: 14px;
    font-weight: 600;
    color: #607d8b;
    margin-left:6px;
    cursor: pointer;
  }
}
.operateBtn{
  display: inline-block;
  position: absolute;
  right: 20px;
  top: 22px;
}
.breadCrumb {
  width: 100%;
  line-height: 40px;
  border-top: 1px solid @garyA300;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  .bread-li {
    margin-right: 10px;
    display: flex;
    align-items: center;
    .bread-title {
      margin-right: 10px;
      cursor: pointer;
      font-weight: bold;
      &:hover {
        opacity: 0.6;
      }
    }
  }
}
.operateBtn{
    /deep/ .ivu-upload{
    display: inline-block;
  }
}

</style>
